package com.qianjiangcloud.store.activity.account;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.qianjiangcloud.store.BaseDoFragment;
import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.util.Util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.NumberFormat;
import java.util.ArrayList;

import com.qianjiangcloud.store.R;

public class InvoiceEditorFragment extends BaseDoFragment implements
        OnCheckedChangeListener {
    private JSONObject mInvoiceInfo = new JSONObject();

    private EditText mInvoiceTitleText;
    private Button mInvoiceContent;
    private RadioButton mNormalRadio;
    private RadioButton mCompanyRadio;
    private RadioButton mNulllRadio;

    private ArrayList<String> types=new ArrayList<String>();
    private ViewGroup invoice_rl1;
    private ViewGroup invoice_rl2;
    private ViewGroup invoice_rl3;
    private int isChecked;//判断是否选着
    public final int SELECT_NO_INVOICE = 0x001;
    public final int SELECT_PERSONAL_INVOICE = 0x002;
    public final int SELECT_COMPANY_INVOICE = 0x003;
    public final ArrayList<JSONObject>  mtax_list=new ArrayList<JSONObject>();



    public InvoiceEditorFragment() {
        super();

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String jsonStr = mActivity.getIntent().getStringExtra(
                Run.INVOICE_DATA);
        try {
            JSONObject all = new JSONObject(jsonStr);
                JSONObject data = all.optJSONObject("data");
                if (data != null) {
                    JSONObject contents = data.optJSONObject("tax_content");


                    types.add(contents.optString("商品清单"));
                    types.add(contents.optString("电器"));
                    types.add(contents.optString("办公用品"));
                    types.add(contents.optString("其它"));
                    JSONArray tax_list= data.optJSONArray("tax_list");

                    for (int i = 0; i < tax_list.length(); i++) {
                        mtax_list.add(tax_list.optJSONObject(i));
                    }
                }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void init(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
        mActionBar.setTitle(R.string.invoice_info);

        rootView = inflater.inflate(R.layout.fragment_invoice, null);
        mInvoiceTitleText = (EditText) findViewById(R.id.invoice_title);
        findViewById(R.id.invoice_submit).setOnClickListener(this);
        findViewById(R.id.invoice_content).setOnClickListener(this);
        mInvoiceContent = (Button) findViewById(R.id.invoice_content);
        //mListView = (ListView) findViewById(R.id.invoice_list);

       TextView select_type_tax_rate_tv= (TextView) findViewById(R.id.select_type_tax_rate_tv);
        select_type_tax_rate_tv.setText("\t"+formToPercentage(mtax_list.get(1).optString("tax_ratio")));
        TextView select_type_tax_rate_tv3= (TextView) findViewById(R.id.select_type_tax_rate_tv3);
        select_type_tax_rate_tv3.setText("\t"+formToPercentage(mtax_list.get(2).optString("tax_ratio")));
       // invoiceDetails = new GetInvoiceDetails();
        //mListView.setAdapter(invoiceDetails);
        //不开发票
        invoice_rl1 = (ViewGroup) findViewById(R.id.invoice_rl1);
        //个人发票
        invoice_rl2 = (ViewGroup) findViewById(R.id.invoice_rl2);
        //公司发票
        invoice_rl3 = (ViewGroup) findViewById(R.id.invoice_rl3);
        invoice_rl1.setOnClickListener(this);
        invoice_rl2.setOnClickListener(this);
        invoice_rl3.setOnClickListener(this);

        mNormalRadio = (RadioButton) findViewById(R.id.invoice_person_radio);
        mCompanyRadio = (RadioButton) findViewById(R.id.invoice_company_radio);
        mNulllRadio = (RadioButton) findViewById(R.id.invoice_null_radio);
        //填充发票内容
        for (int i=0;i<types.size();i++)
        {
            upListView(types.get(i));
        }
        mNulllRadio.setOnCheckedChangeListener(this);
        mNormalRadio.setOnCheckedChangeListener(this);
        mCompanyRadio.setOnCheckedChangeListener(this);
        try {
            String jsonStr = mActivity.getIntent().getStringExtra(
                    Run.EXTRA_DATA);
            mInvoiceInfo = new JSONObject(jsonStr);
//            mInvoiceTitleText.setText(mInvoiceInfo.optString("dt_name"));
//            Util.savePrefs(mActivity, "isChecked", isChecked);
//            Util.savePrefs(mActivity, "dt_name", mInvoiceTitleText.getText()
//                    .toString());
//            Util.savePrefs(mActivity, "index", index);
          int mIsChaecked=  Util.loadOptionInt(mActivity, "isChecked", 0);
            if (mIsChaecked==0)
            {
                isChecked=SELECT_NO_INVOICE;
                getss(invoice_rl1);
                onSelectChanged(SELECT_NO_INVOICE);
            }else{
            ViewGroup view=    mIsChaecked==SELECT_NO_INVOICE?invoice_rl1:mIsChaecked==SELECT_PERSONAL_INVOICE?invoice_rl2:invoice_rl3;
                isChecked=mIsChaecked;
                getss(view);
                onSelectChanged(isChecked);
                payInfo=Util.loadOptionString(mActivity,"detail","");
                mInvoiceTitleText.setText(Util.loadOptionString(mActivity, "dt_name", ""));
                ViewGroup item = ((ViewGroup) findViewById(R.id.confirm_order_pay_items));
                int mindex=  Util.loadOptionInt(mActivity,"index",0);
                ((TextView) item.getChildAt(mindex).findViewById(R.id.confirm_order_pay_name)).setTextColor(mActivity.getResources().getColor(R.color.fragment_invoice_select));
                ((CheckBox) item.getChildAt(mindex).findViewById(R.id.confirm_order_pay_checkbox)).setChecked(true);
            }

       } catch (Exception e) {
       }


        viewGroups.add(invoice_rl1);
        viewGroups.add(invoice_rl2);
        viewGroups.add(invoice_rl3);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {

            int visible = (buttonView == mNulllRadio) ? View.GONE
                    : View.VISIBLE;
            findViewById(R.id.invoice_content_item).setVisibility(visible);
            findViewById(R.id.invoice_title_item).setVisibility(visible);
        }
    }

    public ViewGroup onSelectChanged(int view) {
        if (SELECT_NO_INVOICE == view) {
            setVisibilitystate(invoice_rl1);
            return invoice_rl1;
        } else if (SELECT_PERSONAL_INVOICE == view) {
            setVisibilitystate(invoice_rl2);
            return invoice_rl2;
        } else {
            setVisibilitystate(invoice_rl3);
            return invoice_rl3;

        }


    }

    public void setVisibilitystate(View view) {
        int visible = (view == invoice_rl1) ? View.GONE
                : View.VISIBLE;
        findViewById(R.id.invoice_content_item).setVisibility(visible);
        findViewById(R.id.invoice_title_item).setVisibility(visible);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.invoice_submit) {
            Intent data = new Intent();
            // 不开发票，直接返回
            if (isChecked == SELECT_NO_INVOICE) {
                mActivity.setResult(Activity.RESULT_OK, data);
                mActivity.finish();
                Util.savePrefs(mActivity, "isChecked", 0);
                return;
            }

//			RadioButton checkedRadio = mNormalRadio.isChecked() ? mNormalRadio
//					: mCompanyRadio;
            ViewGroup view = onSelectChanged(isChecked);

            if (!TextUtils.isEmpty(mInvoiceTitleText.getText())
                    && !TextUtils.isEmpty(payInfo.toString())) {
                try {
                    //发票类型
                    mInvoiceInfo.put("type", view.getChildAt(1).getTag().toString());
                    //发票文本
                    mInvoiceInfo.put("type_name", ((TextView) view.getChildAt(1)).getText()
                            .toString());

                    //发票抬头
                    mInvoiceInfo.put("dt_name", mInvoiceTitleText.getText()
                            .toString());
                    //税率
                String  tax_ratio=   view==invoice_rl2?mtax_list.get(1).optString("tax_ratio"):mtax_list.get(2).optString("tax_ratio");
                    mInvoiceInfo.put("tax_ratio", tax_ratio);
//
//                    mInvoiceInfo.put("content", mInvoiceContent.getText()
//                            .toString());
                    mInvoiceInfo.put("detail", payInfo);
                    data.putExtra(Run.EXTRA_DATA, mInvoiceInfo.toString());
                    mActivity.setResult(Activity.RESULT_OK, data);
                   //保存选择后的发票信息
                    savaInvoiceConfig();

                    mActivity.finish();
                } catch (Exception e) {
                }
            }
        } else if (v.getId() == R.id.invoice_content) {
////			types = { "食品", "日用品", "劳保用品", "商品明细" };
//            final CustomDialog mDialog = new CustomDialog(mActivity);
//            mDialog.setTitle(R.string.invoice_content);
//            mDialog.setSingleChoiceItems(types, -1, new OnItemClickListener() {
//                @Override
//                public void onItemClick(AdapterView<?> parent, View view,
//                                        int pos, long id) {
//                    mDialog.dismiss();
//                    try {
//                        mInvoiceInfo.put("detail", types[pos]);
//                        ((TextView) findViewById(R.id.invoice_content))
//                                .setText(types[pos]);
//                    } catch (Exception e) {
//                    }
//                }
//            }).setCancelable(true).show();
        } else if (v.getId() == R.id.invoice_rl1) {
            isChecked = SELECT_NO_INVOICE;
            settingDefault();
            getss(invoice_rl1);

        } else if (v.getId() == R.id.invoice_rl2) {
            getss(invoice_rl2);
            settingDefault();
            isChecked = SELECT_PERSONAL_INVOICE;

        } else if (v.getId() == R.id.invoice_rl3) {
            isChecked = SELECT_COMPANY_INVOICE;
            settingDefault();
            getss(invoice_rl3);


        } else {
            super.onClick(v);
        }
        onSelectChanged(isChecked);
    }
//保留选择后发票配置信息
    private void savaInvoiceConfig() {
        Util.savePrefs(mActivity,"isChecked",isChecked);
        Util.savePrefs(mActivity,"dt_name",mInvoiceTitleText.getText()
                .toString());
        Util.savePrefs(mActivity, "index", index);
        Util.savePrefs(mActivity,"detail",payInfo);

    }


    ArrayList<ViewGroup> viewGroups = new ArrayList<ViewGroup>();

    public void getss(ViewGroup v) {

        for (int i = 0; i < viewGroups.size(); i++) {
            if (viewGroups.get(i) != v) {
                viewGroups.get(i).setBackgroundResource(R.drawable.invoice_btn_general);
                ((ImageView)viewGroups.get(i).getChildAt(0)).setImageResource(R.drawable.no_select);
                ((TextView) viewGroups.get(i).getChildAt(1)).setTextColor(this.getResources().getColor(R.color.text_invoice));
                if (viewGroups.get(i) == invoice_rl2 || viewGroups.get(i) == invoice_rl3) {
                    ((TextView) viewGroups.get(i).getChildAt(2)).setTextColor(this.getResources().getColor(R.color.text_invoice));
                }
            }
        }

        v.setBackgroundResource(R.drawable.invoice_btn_down);
        ((ImageView) v.getChildAt(0)).setImageResource(R.drawable.select_centre);
        ((TextView) v.getChildAt(1)).setTextColor(this.getResources().getColor(R.color.fragment_invoice_select));
        if (v == invoice_rl2 || v == invoice_rl3) {
            ((TextView) v.getChildAt(2)).setTextColor(this.getResources().getColor(R.color.fragment_invoice_select));
        }
    }
public void upListView(String str)
{
    LayoutInflater inf = mActivity.getLayoutInflater();
    View mItem = inf.inflate(R.layout.invoice_details_list_item, null);
    ((TextView) mItem.findViewById(R.id.confirm_order_pay_name)).setText(str);
    ((ViewGroup) findViewById(R.id.confirm_order_pay_items)).addView(mItem);
    mItem.setOnClickListener(mPayListener);
    mItem.setTag(str);
}

    //将String类型的转化成百分比
    public String formToPercentage(String a)
    {
        double  aa=Double.parseDouble(a);
        NumberFormat nt = NumberFormat.getPercentInstance();
        nt.setMinimumFractionDigits(2);
        return nt.format(aa);
    }
    private String payInfo;
    private int index;
    private View.OnClickListener mPayListener = new View.OnClickListener() {




        @Override
        public void onClick(View v) {
            if (v.getTag() != null) {
                String data = (String) v.getTag();
                ViewGroup items = ((ViewGroup) findViewById(R.id.confirm_order_pay_items));
                // 选中当前付款方式
                payInfo = data;
                if ("商品清单".equals(payInfo.toString()))
                {
                    index = 0;
                }
                if ("电器".equals(payInfo.toString()))
                {
                     index=1;
                }
                if ("办公用品".equals(payInfo.toString()))
                {
                     index=2;
                }
                if ("其它".equals(payInfo.toString()))
                {
                     index=3;
                }

                    try {
//                        有异常
                        mInvoiceInfo.put("detail",  v.getTag().toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                for (int i = 0, c = items.getChildCount(); i < c; i++) {
                    ((TextView) items.getChildAt(i).findViewById(R.id.confirm_order_pay_name)).setTextColor(mActivity.getResources().getColor(R.color.text_invoice));
                    ((CheckBox) items.getChildAt(i).findViewById(R.id.confirm_order_pay_checkbox)).setChecked(false);
                }
                ((CheckBox) v.findViewById(R.id.confirm_order_pay_checkbox)).setChecked(true);
                ((TextView) v.findViewById(R.id.confirm_order_pay_name)).setTextColor(mActivity.getResources().getColor(R.color.fragment_invoice_select));
            }
        }
    };

    public void settingDefault()
    {
        payInfo="商品清单";
        mInvoiceTitleText.setText("");
        ViewGroup items= (ViewGroup) findViewById(R.id.confirm_order_pay_items);
        for (int i = 0, c = items.getChildCount(); i < c; i++) {
            ((TextView) items.getChildAt(i).findViewById(R.id.confirm_order_pay_name)).setTextColor(mActivity.getResources().getColor(R.color.text_invoice));
            ((CheckBox) items.getChildAt(i).findViewById(R.id.confirm_order_pay_checkbox)).setChecked(false);
        }
        ((CheckBox) items.getChildAt(0).findViewById(R.id.confirm_order_pay_checkbox)).setChecked(true);
        ((TextView) items.getChildAt(0).findViewById(R.id.confirm_order_pay_name)).setTextColor(mActivity.getResources().getColor(R.color.fragment_invoice_select));
    }
}
